<template>
  <div class="app-container">
    <div class="mapDiv">
      <!--地图-->
      <IndexMap v-if="completeRefreshData==true"
                :allRadioIndexData="allRadioIndexData"
                :allListData="allListData"
                :typeCodeDataList="typeCodeDataList"
                :resetClearAllBool="resetClearAllBool"
                :dataTypeInfoArray="dataTypeInfoArray"
                :mapDrawType="mapDrawType"
                :circleForm="circleForm"
                :tableData="tableData"
                @getDetailDataById="getDetailDataById"
                @getLegendHtml="getLegendHtml"
                @getDownloadName="getDownloadName"
                @getAllDrawGeom="getAllDrawGeom"
      ></IndexMap>
    </div>
    <div id="indexMap-mapDiv" class="ol-popup">
      <!--图层图例-->
      <div v-if="showHideLegendDivBool" class="layerMap-legend">
        <!--滚动条-->
        <el-scrollbar max-height="500px">
          <p>图例</p>
          <div v-for="item in layerShowHideArray" :key="item.code" v-show="item.show" v-html="item.legendHtml">
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup>
  //地图
  import IndexMap from '@/map/achievementSearch/indexMap.vue';
  import { iServerHttp } from "@/map/projMap.js"
  import { getDict } from '@/api/system/dict'
  import { spaceDataTableInfoList } from '@/views/achievementSearch/spaceDataLayer.js'

  const props = defineProps(['twoCheck','selectSmId','mapDrawType','circleForm','tableData']);
  const emits = defineEmits(['getAllDrawGeomText'])
  const { proxy } = getCurrentInstance();
  const router = useRouter()

  /*地图传参start*/
  const completeRefreshData = ref(false);//防止刷新后地图不显示
  const allListData = ref([]);//地图显示数据列表
  const typeCodeDataList = ref([]);//选择图层的版本号数据列表
  const allRadioIndexData = ref([]);//全部序号列表
  const resetClearAllBool = ref(false);//是否重置清空全部图层数组
  //数据类型
  const dataTypeInfoArray = ref([
    ////////////////////////活动断层数据系统
  ]);
  const showHideLegendDivBool = ref(false);//是否显示图例
  const layerShowHideArray = ref([]);//图层是否显示数组
  //图例
  const getLegendHtml = (obj)=>{
    //图层显示隐藏数组
    let showHideArray = layerShowHideArray.value;
    if(obj!=null){
      for(let i=0;i<showHideArray.length;i++){
        if(showHideArray[i].name==obj.name){
          showHideArray[i].show = obj.show;
          showHideArray[i].legendHtml = obj.legendHtml;//显示图例
          break;
        }
      }
      //是否显示图例
      let bool = false;
      for(let i=0;i<showHideArray.length;i++){
        if(showHideArray[i].show){
          bool = true;
          break;
        }
      }
      showHideLegendDivBool.value = bool;
    }else{//清空图例
      //是否显示图例
      for(let i=0;i<showHideArray.length;i++){
        showHideArray[i].show = false;
      }
      showHideLegendDivBool.value = false;
    }
  }

  //根据ID查询数据属性表
  const getDetailDataById = (temp)=>{
    if(temp.id && temp.typeCode){
      let dataTypeInfo = temp.dataTypeInfo;
      let code = temp.typeCode;
      let id = temp.id;
      let smId = temp.smId;//专题ID
      let typeName = dataTypeInfo.name;
      // code:"Pt1"
      // id:"646f72a69b984ea48b36a77516363ca0"
      // smId:"bac8ff689ea24d1d985471755dc9994e"
      // typeName:"微地貌测量采样点-点"
      router.push({ path: `/achievementSearch/index/${code}`, query: { id: smId, detailId: id, typeName } })
    }
  }
  //下载文件
  const getDownloadName = (name)=>{
    importTemplate(name);
  }
  /*地图传参end*/

  //设置图例数组
  function setLayerShowHideArray(){
    let showHideArray = [];
    let dataTypeArray = dataTypeInfoArray.value;
    for(let i=0;i<dataTypeArray.length;i++){
      let item = dataTypeArray[i];
      showHideArray.push({ code: item.code, name: item.name, show:false,legendHtml:"" });
    }
    layerShowHideArray.value = showHideArray;
  }

  //查询字典获取全部数据类型列表
  function getAllDataTypeInfoArray(){
    getDict('SpaceData').then(res => {
      let resultList = [];
      let list = res.data;
      if(list && list.length>0){
        let count = 0;
        for(let i=0;i<list.length;i++){
          let dictItemCode = list[i].dictItemCode;
          getDict(dictItemCode).then(res => {
            let dictList = res.data;
            if(dictList && dictList.length>0){
              for(let i=0;i<dictList.length;i++){
                let dictData = dictList[i];
                //获取数据类别信息
                let obj = getSpaceDataInfoByDictData(dictData);
                resultList.push(obj);
              }
            }
            count++;
            if(list.length==count){
              dataTypeInfoArray.value = resultList;
              console.log("dataTypeInfoArray");
              console.log(resultList);
              setLayerShowHideArray();//设置图例数组
              initAllLayerDataArray();//初始化设置全部超图图层所需数据
            }
          })
        }
      }
    })
  }

  //获取数据类别信息
  function getSpaceDataInfoByDictData(dictData){
    let obj = {
      database:"fxfzhddc",
      name: dictData.dictItemName,
      label: dictData.dictItemName,
      radioLabel: dictData.dictItemCode,
      code: dictData.dictItemCode,
      table:dictData.description,
      url:iServerHttp()+"/iserver/services/map-fxfzhddc/rest/maps/"+dictData.description+"@fxfzhddc",
      zIndex:8,
      fieldId:"",//主键ID
      sqlFilter:"",
      show:false,
      // layerName:dictData.description+"@fxfzhddc",//图层名
    };
    //空间数据表信息
    for(let i=0;i<spaceDataTableInfoList.length;i++){
      if(spaceDataTableInfoList[i].table==dictData.description){
        obj.fieldId = spaceDataTableInfoList[i].fieldId;
        obj.zIndex = spaceDataTableInfoList[i].zIndex;
        break;
      }
    }

    return obj;
  }

  //初始化设置全部超图图层所需数据
  function initAllLayerDataArray(){
    let typeCodeDataArray = [];
    let allRadioIndexArray = [];
    let childrenData = [];
    let list = dataTypeInfoArray.value;
    if(list!=null && list.length>0){
      for(let i=0;i<list.length;i++){
        let data = list[i];
        childrenData.push({
          name: data.name,
          radioLabel: data.code,
          dictItemCode: data.code,
          spaceBool:true,//是否空间数据
        });
        //选择图层的版本号数据列表
        typeCodeDataArray.push({
          name: data.name,
          radioLabel: data.code,
          dictItemCode: data.code,
          spaceBool:true,//是否空间数据
          typeCodeSelectData:[],
          sqlFilter:data.sqlFilter,//sql过滤条件
        });
        //全部序号列表
        allRadioIndexArray.push(data.code);
      }
    }
    //选择图层的版本号数据列表
    typeCodeDataList.value = typeCodeDataArray;
    //全部序号列表
    allRadioIndexData.value = allRadioIndexArray;
  }

  //下载文件
  function importTemplate(name) {
    proxy.download("/base/product/downloadExcel", {
      fileName:name
    }, name);
  }

  //勾选图层列表
  const checkList = ref([]);
  //获取勾选图层列表
  const getCheckList = (selectList) => {
    console.log("获取勾选图层列表");
    console.log(selectList);
    checkList.value = selectList;//勾选图层列表
    //根据勾选图层列表显示隐藏图层
    showHideLayer();
  }

  //根据勾选图层列表显示隐藏图层
  function showHideLayer(){
    let selectList = checkList.value;//勾选图层列表
    let list = dataTypeInfoArray.value;
    for(let i=0;i<list.length;i++){
      let code = list[i].code;
      let bool = false;
      if(selectList && selectList.length>0){
        for(let j=0;j<selectList.length;j++){
          let selectCode = selectList[j];
          if(selectCode==code){
            bool = true;
            break;
          }
        }
      }
      list[i].show = bool;//是否显示图层
    }
    dataTypeInfoArray.value = list;
    console.log(list);
    //根据数据类别code、版本号查询图层
    getLayerByVersionDataType(0);
  }

  //清空全部图层
  function clearAllLayer(){
    //隐藏全部图层
    let list = dataTypeInfoArray.value;
    for(let i=0;i<list.length;i++){
      list[i].show = false;//是否显示图层
    }
    dataTypeInfoArray.value = list;
    //清空版本号列表
    let datalist = typeCodeDataList.value;
    for(let i=0;i<datalist.length;i++){
      //设置图层对应的选择版本号列表
      datalist[i].typeCodeSelectData = [];
    }
    typeCodeDataList.value = datalist;
    //是否重置清空全部图层数组
    resetClearAllBool.value = true;
  }

  //根据三级数据类别获取版本数据
  const getLayerInfoByDictItemCode = (dictItemCode) => {
    let data = null;
    let datalist = typeCodeDataList.value;
    for(let i=0;i<datalist.length;i++){
      if(datalist[i].dictItemCode==dictItemCode){
        data = datalist[i];
        break;
      }
    }
    return data;
  }

  //设置图层选择的版本号列表（添加、移除）并查询图层数据
  function setActiveTypeCodeList(versionCode,typeCode,showBool){
    //根据三级数据类别获取版本数据
    let data = getLayerInfoByDictItemCode(typeCode);
    if(data!=null && versionCode){
      let typeCodeSelectArray = data.typeCodeSelectData;
      let bool = null;//是否添加版本号
      //添加、移除版本号
      if (!typeCodeSelectArray.includes(versionCode)) {
        if(showBool){
          typeCodeSelectArray.push(versionCode);//添加
          bool = true;
        }
      } else {
        typeCodeSelectArray.forEach((id, index) => {
          if (id === versionCode) {
            if(showBool==false){
              typeCodeSelectArray.splice(index, 1);//移除
              bool = false;
            }
          }
        });
      }
      //设置图层对应的选择版本号列表
      data.typeCodeSelectData = typeCodeSelectArray;
      //选中图层查询范围的专题ID
      if(props.selectSmId){
        data.sqlFilter = "sm_id='"+props.selectSmId+"'";//sql过滤条件
      }else{
        data.sqlFilter = "";
      }
      resetClearAllBool.value = false;//是否重置清空全部图层数组
      //空间数据
      if(showBool && bool){//添加版本号
        //根据图层类型查询图层版本号数据
        allListData.value = [typeCode,versionCode,[],true,null];
        return true;
      }else if(showBool==false && bool==false){//移除版本号
        allListData.value = [typeCode,versionCode,[],false,null];
        return true;
      }
    }
    return false;
  }

  //根据数据类别code、版本号查询图层
  function getLayerByVersionDataType(i){
    let list = dataTypeInfoArray.value;
    if(i<list.length){
      let typeCode = list[i].code;//数据类别三级code
      let versionCode = "全部";//版本号："全部"则展示整个图层，null无版本号不展示
      let showBool = list[i].show;//是否显示
      //设置图层选择的版本号列表（添加、移除）并查询图层数据
      let returnBool = setActiveTypeCodeList(versionCode,typeCode,showBool);
      if((i+1)<list.length){
        if(returnBool){
          console.log(typeCode+"--returnBool"+returnBool);
          setTimeout(function(){
            //根据数据类别code、版本号查询图层
            getLayerByVersionDataType(i+1);
          },1000);
        }else{
          //根据数据类别code、版本号查询图层
          getLayerByVersionDataType(i+1);
        }
      }
    }
  }

  //地图圈选
  const mapDrawType = ref("");//是否开启地图圈选查询类型（StopDraw关闭地图圈选 Polygon多边形绘制 Clear清空）
  //全部地图绘制空间数据
  const allDrawGeomText = ref("");
  //获取全部地图绘制结果
  const getAllDrawGeom = (list) =>{
    console.log("获取全部地图绘制结果");
    console.log(list);
    if(list && list.length>0){
      allDrawGeomText.value = list[0];//全部地图绘制空间数据
    }else{
      allDrawGeomText.value = "";
    }
    mapDrawType.value = "StopDraw";
    emits("getAllDrawGeomText",allDrawGeomText.value);
  }

  //获取勾选图层code列表
  const getCheckCodeLists = watch(() => props.twoCheck, value => {// watch函数监听props.twoCheck
    console.log("twoCheck");
    console.log(value);
    if(value && value.length>0){
      //获取勾选图层列表
      getCheckList(value);
    }else{
      //清空全部图层
      clearAllLayer();
    }
  },{immediate:true});

  //获取选中图层查询范围的专题ID
  const getSelectSmId = watch(() => props.selectSmId, value => {// watch函数监听props.selectSmId
    if(value){
      console.log("获取选中图层查询范围的专题ID--"+value);
      //清空全部图层
      clearAllLayer();
      setTimeout(function(){
        //根据勾选图层列表显示隐藏图层
        showHideLayer();
      },200);
    }
  },{immediate:true});

  //获取地图圈选类型
  const getMapDrawType = watch(() => props.mapDrawType, value => {// watch函数监听props.mapDrawType
    if(value){
      mapDrawType.value = value;
    }
  },{immediate:true});

  const circleForm = ref([]);
  //获取表格数据
  const getCircleForm = watch(() => props.circleForm, value => {// watch函数监听props.circleForm
    if(value){
      circleForm.value = value;
    }
  },{immediate:true});

  const tableData = ref([]);
  //获取表格数据
  const getTableData = watch(() => props.tableData, value => {// watch函数监听props.tableData
    if(value){
      tableData.value = value;
    }
  },{immediate:true});

  onMounted(() => {
    //查询字典获取全部数据类型列表
    getAllDataTypeInfoArray();
    //显示地图模块
    completeRefreshData.value = true;
  });


</script>

<style scoped lang="scss">
  .mapDiv {
    position:absolute;top:0px;left:0px;width:100%;height:100%;
  }

  //图例
  .layerMap-legend {
    position: absolute;
    right: 10px;
    bottom: 10px;
    min-height: 50px;
    background: #fff;
    padding: 10px;
    overflow: auto;
    min-width: 200px;
    box-shadow: 0px 0px 20px rgba(0,0,0,0.2);
    border:1px solid #707070;
    border-radius: 4px;
  }
  .layerMap-legend p:first-child{
    text-align: center;font-weight: bold;
  }

  .operation-panel-right {
    position: absolute;
    top: 0;
    z-index: 9;
    font-weight: bold;
    right: 0;

    .el-card {
      .operation-item {
        text-align: center;
        cursor: pointer;

        &>.operation-item-icon {
          transform: scale(1.2);
          margin: 0 0 5px 0;
          &:hover, &:active{
            color: var(--el-color-primary);;
          }
        }

        &:not(:last-child) {
          margin-bottom: 20px;
        }
      }
    }
  }

  .ol-attribution {
    display:none;
  }

</style>